<template>
    <div>
        <el-card class="mb-10">
            <CategorySelector :disabled="isEdit"></CategorySelector>
        </el-card>
        <el-card>
            <!-- 列表展示区域 -->
            <div v-show="!isEdit">
                <el-button class="mb-10" type="primary" :icon="Plus" :disabled="!categoryStore.category3Id"
                    @click="addAttr">添加属性</el-button>
                <el-table :data="attrList" border>
                    <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
                    <el-table-column label="属性名" width="160" prop="attrName"></el-table-column>
                    <el-table-column label="属性值列表">
                        <template #default="{ row, $index }">
                            <el-tag class="mr-5" type="success" v-for="attrVal in row.attrValueList"
                                :key="attrVal.id">{{ attrVal.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="140">
                        <template #default="{ row, $index }">
                            <el-button type="warning" size="small" :icon="Edit" @click="editAttr(row)"></el-button>

                            <el-popconfirm :title="`确认要删除[${row.attrName}]`" @confirm="deleteAttr(row)">
                                <template #reference>
                                    <el-button type="danger" size="small" :icon="Delete"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 新增编辑展示 -->
            <div v-show="isEdit">
                <el-form :inline="true">
                    <el-form-item label="属性名">
                        <el-input type="text" v-model="attrForm.attrName" placeholder="输入属性名"></el-input>
                    </el-form-item>
                </el-form>
                <div class="mb-10">
                    <el-button type="primary" @click="addAttrVal" :disabled="!attrForm.attrName">添加属性值</el-button>
                    <el-button @click="cancelSave">取消</el-button>
                </div>
                <el-table :data="attrForm.attrValueList" class="mb-10" border>
                    <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #default="{ row, $index }">
                            <el-input v-if="row.inputVisible" ref="inputRef" v-model="row.valueName"
                                @blur="inputBlur(row, $index)"></el-input>
                            <div v-else @click="inputFocus(row)">{{ row.valueName }}</div>
                        </template>

                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template #default="{ row, $index }">
                            <el-button type="danger" size="small" :icon="Delete"
                                @click="deleteAttrVal($index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div>
                    <el-button type="primary" @click="onSave"
                        :disabled="!(attrForm.attrName && attrForm.attrValueList.length)">保存</el-button>
                    <el-button @click="cancelSave">取消</el-button>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from 'vue';
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import attrApi, { type AttrModel, type AttrValueModel } from '@/api/attr'
import useCategoryStore from '@/stores/category';
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash';
const categoryStore = useCategoryStore(); // 拿到三级分类的store
const isEdit = ref(false)// 默认不是编辑状态

const inputRef = ref<HTMLInputElement>()// 拿到当前input的实例
// input聚焦事件
const inputFocus = (row: AttrValueModel) => {
    row.inputVisible = true;
    nextTick(() => {
        inputRef.value?.focus()
    })
}

//input 失焦事件
const inputBlur = (row: AttrValueModel, index: number) => {
    row.inputVisible = false;
    // 判断输入的内容不能为空
    if (!row.valueName.trim()) {
        attrForm.value.attrValueList.splice(index, 1)// 删除掉这条空数据
        ElMessage.error('输入的内容不能为空')
        return
    }

    // 判断输入的内容不能重复
    // attrForm.value.attrValueList  属性值列表
    // row 当前属性值
    // 在属性值列表中,一定有当前自己的这个属性值(row),判断的时候,需要把自己在数组中的位置排除掉之后,再进行判断有没有相同的
    const isRepeat = attrForm.value.attrValueList.some((item, idx) => {
        if (index == idx) {// 把自己排除掉
            return false
        } else {
            return item.valueName == row.valueName
        }
    })
    if (isRepeat) {
        attrForm.value.attrValueList.splice(index, 1)
        ElMessage.error('输入的内容不能重复，请重新输入')
        return
    }
}




// 删除平台属性
const deleteAttr = async (row: AttrModel) => {
    try {
        await attrApi.deleteAttr(row.id as number)
        ElMessage.success('删除成功')
        getList()// 重新获取数据进行显示
    } catch (error) {
        ElMessage.error('删除失败，请重试')
    }
}







// 新增界面展示
const addAttr = () => {
    isEdit.value = true
}
// 初始化 attrForm
const initAttrForm = (): AttrModel => ({
    attrName: '',
    attrValueList: [],
    categoryId: undefined,
    categoryLevel: 3
})
// 准备好即将要收集的数据
const attrForm = ref<AttrModel>(initAttrForm())

// 编程回调
const editAttr = (row: AttrModel) => {
    isEdit.value = true;// 切换编辑页面
    attrForm.value = cloneDeep(row);// 回显数据
}





// 添加属性值
const addAttrVal = () => {
    attrForm.value.attrValueList.push({
        valueName: '',// 目前随便写一个值,不要为空即可,后期回来在改
        inputVisible: true // 用这个数据来控制当前这个对象在表格中切换input的显示状态
    })
    nextTick(() => {
        inputRef.value?.focus()// 等待DOM更新,拿到组件实例进行自动聚焦
    })
}

// 删除属性值
const deleteAttrVal = (index: number) => {
    // attrForm.value.attrValueList 属性值列表删除数据
    attrForm.value.attrValueList.splice(index, 1)// 删除一个属性值
}


// 保存
const onSave = async () => {
    // 收集categoryId的值 - 组装数据
    attrForm.value.categoryId = categoryStore.category3Id
    // 调用接口
    try {
        await attrApi.saveAttr(attrForm.value)
        ElMessage.success('保存成功')
        cancelSave()// 取消的回调
        getList() // 刷新主列表的数据
    } catch (error) {
        ElMessage.error('保存失败，请重试')
    }
}


// 取消保存
const cancelSave = () => {
    isEdit.value = false;// 切换主界面显示
    attrForm.value = initAttrForm()// 重置表单数据
}


// 列表展示数据
const attrList = ref<AttrModel[]>([])

// 初始化数据的请求
const getList = async () => {
    try {
        const { category1Id, category2Id, category3Id } = categoryStore;
        let result = await attrApi.attrInfoList(category1Id as number, category2Id as number, category3Id as number)
        attrList.value = result
    } catch (error) {
        ElMessage.error('获取列表数据失败,请重试')
    }
}

// 只要三级id有,那么就去获取数据
watch(() => categoryStore.category3Id, (nval) => {
    if (nval) {
        getList()
    } else {
        attrList.value = []
    }
}, { immediate: true })
</script>

<style scoped>

</style>